package io.kiki.sba.registry.server.clientInterface.remoting.handler;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.Node.NodeType;
import io.kiki.sba.registry.common.model.sessionserver.DataPushRequest;
import io.kiki.sba.registry.server.clientInterface.bootstrap.Config;
import io.kiki.sba.registry.server.clientInterface.bootstrap.ExecutorManager;
import io.kiki.sba.registry.server.clientInterface.push.FirePushService;
import io.kiki.sba.registry.server.clientInterface.push.PushSwitchService;
import io.kiki.sba.registry.server.shared.remoting.AbstractClientHandler;
import io.kiki.sba.registry.server.shared.remoting.RemotingHelper;
import io.kiki.sba.registry.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.Executor;

/**
 * current for standard env temp publisher push
 */
public class DataPushRequestHandler extends AbstractClientHandler<DataPushRequest> {

    private static final Logger logger = LoggerFactory.getLogger(DataPushRequestHandler.class);

    @Autowired
    FirePushService firePushService;

    @Autowired
    ExecutorManager executorManager;

    @Autowired
    Config config;

    @Autowired
    PushSwitchService pushSwitchService;

    @Override
    public Executor getExecutor() {
        return executorManager.getDataChangeRequestExecutor();
    }

    @Override
    public void checkParam(DataPushRequest request) {
        StringUtil.nullValue(request.getSubDatum(), "request.datum");
    }

    @Override
    protected NodeType getConnectNodeType() {
        return NodeType.data_store;
    }

    @Override
    public Object doHandle(Channel channel, DataPushRequest request) {
        if (!pushSwitchService.canLocalDataCenterPush()) {
            return null;
        }
        try {
            firePushService.fireOnDatum(request.getSubDatum(), RemotingHelper.getRemoteHostAddress(channel));
        } catch (Throwable e) {
            logger.error("DataPush Request error!", e);
            throw new RuntimeException("DataPush Request error!", e);
        }
        return null;
    }

    @Override
    public Class interest() {
        return DataPushRequest.class;
    }
}
